<template>
  <div class="authority-page">
    <!-- 查询条件表单 -->
    <el-form :model="queryParams" inline>
      <el-form-item label="账户ID">
        <el-input v-model="queryParams.account" placeholder="请输入账户ID"></el-input>
      </el-form-item>
      <el-form-item label="平台名称">
        <el-input v-model="queryParams.step" placeholder="请输入平台名称"></el-input>
      </el-form-item>
      <el-form-item label="EAID">
        <el-input v-model="queryParams.ea_id" placeholder="请输入EAID"></el-input>
      </el-form-item>
      <div>
        <el-form-item label="写入时间">
          <el-date-picker v-model="queryParams.datetimeRange" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData">查询</el-button>
          <el-button type="danger" @click="resetFilters">重置</el-button>
        </el-form-item>
        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="openAddDialog">新增数据</el-button>
          <el-button type="primary" @click="exportTemplate">下载模版</el-button>
          <el-button type="success" @click="handleImport">导入数据</el-button>
          <el-button type="success" @click="handleExport">导出数据</el-button>
        </el-form-item>
      </div>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="step" label="平台名称"></el-table-column>
      <el-table-column prop="ea_id" label="EAID"></el-table-column>
      <el-table-column prop="account" label="账户ID"></el-table-column>
      <el-table-column prop="datetime" label="写入时间"></el-table-column>
      <el-table-column prop="begintime" label="开始时间"></el-table-column>
      <el-table-column prop="endtime" label="结束时间"></el-table-column>

      <!-- 自定义操作列 -->
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editItem(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteItem(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination  :current-page="currentPage" :total="total" @size-change="sizeChange" @current-change="handlePageChange"
      :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" background layout="sizes, total, prev, pager, next, jumper">
    </el-pagination>

    <!-- 新增/编辑对话框 -->
    <sys-dialog
    :title="dialog.title"
    :height="dialog.height"
    :width="dialog.width"
    :visible.sync="dialog.visible"
    @onClose="onClose"
    @onConfirm="onConfirm">
      <div slot="content">
        <el-form ref="addModel" :model="addModel" :rules="rules" label-width="80px" size="small">
          <el-row>
            <el-col :span="12" :offset="0">
              <el-form-item prop="step" label="平台名称">
                <el-input v-model="addModel.step" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item prop="ea_id" label="EAID">
                <el-input v-model="addModel.ea_id" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12" :offset="0">
              <el-form-item prop="account" label="账户ID">
                <el-input v-model="addModel.account" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="写入时间">
                <el-date-picker v-model="addModel.datetime" type="datetime" placeholder="请选择写入时间" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12" :offset="0">
              <el-form-item label="开始时间">
                <el-date-picker v-model="addModel.begintime" type="datetime" placeholder="请选择开始时间"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="结束时间">
                <el-date-picker v-model="addModel.endtime" type="datetime" placeholder="请选择结束时间" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </sys-dialog>


  </div>
</template>

<script>
import SysDialog from '@/components/dialog/SysDialog.vue'
export default {
  components: {
    SysDialog
  },
  data() {
    return {
      queryParams: {
        account: '',
        step: '',
        ea_id: '',
        datetimeRange: null,
      },
      tableData: [], // 表格数据
      allData: [], // 模拟的所有数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示条数
      total: 0, // 总条数
      dialog: {
        visible: false,
        title: '',
        height: 300,
        width: 630,
      },
      addModel: {
        step: '',
        ea_id: '',
        account: '',
        datetime: '',
        begintime: '',
        endtime: '',
        type: '0'
      },
      rules: {
        step: [{ required: true, message: '请输入平台名称', trigger: 'blur' }],
        ea_id: [{ required: true, message: '请输入EAID', trigger: 'blur' }],
        account: [{ required: true, message: '请输入账户ID', trigger: 'blur' }],
        datetime: [{ required: true, message: '请选择写入时间', trigger: 'change' }],
        begintime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endtime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
      },
    };
  },
  methods: {
    fetchData() {
      // 筛选条件
      const { account, step, ea_id, datetimeRange } = this.queryParams;

      // 根据条件筛选数据
      let filteredData = this.allData.filter((item) => {
        const accountMatch = !account || item.account.toString().includes(account);
        const stepMatch = !step || item.step.includes(step);
        const eaIdMatch = !ea_id || item.ea_id.includes(ea_id);
        const datetimeMatch =
          !datetimeRange ||
          (new Date(item.datetime) >= new Date(datetimeRange[0]) &&
            new Date(item.datetime) <= new Date(datetimeRange[1]));
        return accountMatch && stepMatch && eaIdMatch && datetimeMatch;
      });

      // 分页数据
      this.total = filteredData.length;
      const start = (this.currentPage - 1) * this.pageSize;
      this.tableData = filteredData.slice(start, start + this.pageSize);
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchData();
    },
    sizeChange(size) {
      console.log(size);
      this.pageSize = size;
      this.fetchData();
    },
    resetFilters() {
      this.queryParams = {
        account: '',
        step: '',
        ea_id: '',
        datetimeRange: null,
      };
      this.fetchData();
    },
    exportTemplate() {
      this.$message.info('导出模板功能待开发');
    },
    handleImport() {
      this.$message.info('导入功能待开发');
    },
    handleExport() {
      this.$message.info('导出功能待开发');
    },
    openAddDialog() {
      this.dialog.title = '新增数据';
      this.addModel = {
        step: '',
        ea_id: '',
        account: '',
        datetime: '',
        begintime: '',
        endtime: '',
        type: '0',
      };
      this.dialog.visible = true;
    },
    onClose() {
      this.addModel = {
        step: '',
        ea_id: '',
        account: '',
        datetime: '',
        begintime: '',
        endtime: '',
      };
      this.dialog.visible = false;
    },
    onConfirm() {
      console.log(this.addModel);
      if (this.addModel.type === '0') {
      const newData = { ...this.addModel, id: this.allData.length + 1 };
      this.allData.push(newData);
      this.fetchData();
      this.$message.success('新增成功');
      this.dialog.visible = false;
      } else if (this.addModel.type === '1'){
      // 更新数据
      const index = this.allData.findIndex(item => item.id === this.addModel.id);
      if (index !== -1) {
        this.allData[index] = { ...this.addModel };
        this.fetchData();
        this.$message.success('更新成功');
        this.dialog.visible = false;
        }
      }

    },
    generateMockData() {
      const steps = ['平台A', '平台B', '平台C', '平台D'];
      const mockData = [];
      for (let i = 1; i <= 20; i++) {
        const step = steps[Math.floor(Math.random() * steps.length)];
        mockData.push({
          id: i,
          step,
          ea_id: `EA${String(i).padStart(3, '0')}`,
          account: Math.floor(1000 + Math.random() * 9000),
          datetime: this.generateRandomDate(),
          begintime: this.generateRandomDate(),
          endtime: this.generateRandomDate(),
        });
      }
      this.allData = mockData;
      this.total = mockData.length;
      this.currentPage = 1; // 重置到第一页
      this.fetchData();
    },
    generateRandomDate() {
      const year = 2024;
      const month = Math.floor(Math.random() * 12); // 0-11
      const day = Math.floor(Math.random() * 28) + 1; // 1-28
      const hour = Math.floor(Math.random() * 24); // 0-23
      const minute = Math.floor(Math.random() * 60); // 0-59
      const second = Math.floor(Math.random() * 60); // 0-59

      // 生成格式化后的日期字符串
      return `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`;
    },
    // 编辑操作
    editItem(row) {
      this.dialog.title = '编辑数据';
        // 将选中的数据赋值给 addModel
      this.addModel = { ...row };
      this.addModel.type = '1';
      // 打开编辑对话框
      this.dialog.visible = true;
    },
    // 删除操作
    deleteItem(row) {
      this.$confirm(`确定删除 ID 为 ${row.id} 的数据吗？`, '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 执行删除操作
        this.allData = this.allData.filter(item => item.id !== row.id);
        this.fetchData(); // 重新加载数据
        this.$message.success('删除成功');
      }).catch(() => {
        this.$message.info('取消删除');
      });
    },
  },
  created() {
    this.generateMockData(); // 生成模拟数据
    this.fetchData();
  },
};
</script>

<style scoped>
.authority-page {
  padding: 20px;
}

.filters {
  margin-bottom: 20px;
}

.table-actions {
  margin-bottom: 20px;
}

.el-form-item {
  margin-right: 20px;
}
</style>
